# -*- coding: utf-8 -*-
"""
输入对话框工具模块 —— Qt6 版（无 VBScript）
"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import configparser
import traceback
from utils.logger        import log
from utils.constants     import EXIT_PWD, STATE_MAP, STATE_COLOR, WORK_STATES, ROLE_MAP, GRACE_SECS, MUTEX_NAME
from ui.qt6_input_dialog import qt_multi_input_box, qt_single_input, qt_combo_input

# ========== 唯一入口：Qt6 单行输入框 ==========
def input_box(title, prompt, mask=False):
    """Qt6 单行输入（子进程，不卡主线程）"""
    result = qt_single_input(title, prompt, password=mask)
    
    # ★★★ 修复：检查用户是否取消输入（返回None）
    if result is None:
        log(f'[INPUT] {title}: {prompt} -> 用户取消输入')
        return None
    
    log(f'[INPUT] {title}: {prompt} -> 用户输入: {"*"*len(result) if mask else result}')
    return result

# ========== 控制台备用 ==========
def console_input_box(title, prompt, mask=False):
    """极端情况才用"""
    try:
        print(f"\n{'='*50}")
        print(f"📝 {title}")
        print(f"💬 {prompt}")
        print('-'*50)
        if mask:
            import msvcrt
            print("🔒 密码输入: ", end='', flush=True)
            pwd = []
            while True:
                ch = msvcrt.getch()
                if ch in (b'\r', b'\n'):
                    print(); break
                elif ch == b'\x08' and pwd:
                    pwd.pop(); print('\b \b', end='', flush=True)
                elif ch == b'\x1b':
                    return None
                else:
                    pwd.append(ch); print('*', end='', flush=True)
            result = b''.join(pwd).decode('utf-8')
        else:
            print("💡 请输入: ", end='', flush=True)
            result = input()
        print('='*50)
        return result if result else None
    except Exception as e:
        log(f'[ERR] 控制台输入失败: {e}')
        return None

# ========== 业务函数 ==========
def verify_password(action_name):
    pwd = input_box('密码验证', f'请输入密码以{action_name}:', mask=True)
    return pwd == EXIT_PWD

def get_user_id(data_dir: str) -> str:
    ini_path = os.path.join(data_dir, 'config.ini')
    if os.path.exists(ini_path):
        cfg = configparser.ConfigParser()
        cfg.read(ini_path, encoding='utf-8')
        return cfg['USER']['id']

    while True:
        uid = input_box('初始化', '请输入你的工号（必填）：')
        if uid and uid.strip() and uid != 'unknown':
            break
        elif uid is None:
            continue  # 重新弹框
    cfg = configparser.ConfigParser()
    cfg['USER'] = {'id': uid.strip()}
    with open(ini_path, 'w', encoding='utf-8') as f:
        cfg.write(f)
    return uid.strip()

def multi_input_box(title: str, prompts: tuple[str, ...], default_values: tuple[str, ...] = None, 
                   header_text: str = "", parent=None) -> list[str] | None:
    if default_values is None:
        default_values = []
    return qt_multi_input_box(
        title=title,
        prompts=prompts,
        default_values=default_values,
        combo_items=[],
        header_text=header_text,  
        parent=parent
    )

def combo_input_box(title="请选择", prompt="请选择一项：", choices=None, default_value=""):
    """Qt6 下拉选择框"""
    if choices is None:
        choices = []
    result = qt_combo_input(title, prompt, choices, default_value)
    log(f'[INPUT] {title}: 用户选择 -> {result}')
    return result

def show_summary_window(data_dir: str, user_id: str):
    """打开Qt6今日汇总窗口"""
    from ui.qt6_summary_window import show_summary_window as _show
    _show(data_dir, user_id)

# ========== 自测 ==========
if __name__ == "__main__":
    try:
        print("----- Qt6 单行输入框自测 -----")
        pwd = qt_single_input("密码验证", "请输入密码：", password=True)
        print("你输入的是：", pwd)

        print("\n----- Qt6 下拉选择框自测 -----")
        choice = qt_combo_input("作业类型", "请选择本次作业类型：", ["数据更新", "初审", "复审"])
        print("你选中的是：", choice)
    except Exception as e:
        print("❌ 出错了：", e)
        traceback.print_exc()